package com.bensonbasement.snorflux.client.states;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.Timer;

import com.bensonbasement.snorflux.client.SnorfluxClient;
import com.bensonbasement.snorflux.memory.RBigEntity;
import com.bensonbasement.snorflux.memory.RSmallEntity;
import com.bensonbasement.snorflux.memory.RSpace;
import com.bensonbasement.snorflux.messages.fromserver.WorldTimeMessage;
import com.bensonbasement.snorflux.messages.fromserver.reports.WalkReport;
import com.bensonbasement.snorflux.utils.Coords;

public class WalkAnimationState extends ConnectedState {
	
	private final Timer timer;
	private int pixelsMoved;
	private final WalkReport report;
	private final Coords startCoords;
	private final Coords offset;
	
	public WalkAnimationState(SnorfluxClient client, WalkReport report) {
		super(client);
		this.report = report;
		startCoords = getCoordsInPanel(report.getOrigin().getCoords());
		offset = report.getWalkDirection().getCoords();
		pixelsMoved = 0;
		ActionListener timerListener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				pixelsMoved += 8;
				if (pixelsMoved >= 32) {
					finishAnimation();
				}
				else {
					getMapPanel().repaint();
				}
			}
		};
		timer = new Timer(40,timerListener);
	}
	
	@Override
	public void initialize() {
		super.initialize();
		getWorldUpdateManager().animationStart();
		timer.start();
		getMapPanel().repaint();
	}
	
	@Override
	public void drawMapPanel(Graphics g) {
		super.drawMapPanel(g);
		Coords drawCoords = startCoords.plus(offset.times(pixelsMoved));
		Image actorImage = getWarehouse().getImage(report.getActorGlyph());
		g.drawImage(actorImage, drawCoords.getX(), drawCoords.getY(), null);
	}
	
	@Override
	protected void drawBigEntity(Graphics g, RSpace space, Coords drawCoords) {
		// Don't draw the actor the way we normally would.
		RBigEntity bigEntity = space.getBigEntity();
		if (bigEntity != null && bigEntity.getWorldElementID() != report.getActorID()) {
			super.drawBigEntity(g, space, drawCoords);
		}
	}
	
	@Override
	public void handleWorldTimeMessage(WorldTimeMessage message) {
		throw new RuntimeException("Should not receive a WorldTimeMessage while animating.");
	}
	
	private void finishAnimation() {
		timer.stop();
		changeState(new IdleState(client));
	}
}
